In a member function declaration or definition, override specifier ensures that the function is virtual and is overriding a virtual function from a base class. The program is ill-formed (a compile-time error is generated) if this is not true.
override is an identifier with a special meaning when used after member function declarators: it's not a reserved keyword otherwise.
使用override来避免上述方式如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Base
{
public:
virtualvoidf()
{
std::cout << "Base::f()";
}
};
class Derived : public Base
{
public:
virtualvoidf() override
{
std::cout << "Derived::f() const";
}
};
此时,如果像前面那样,在子类中新增一个const关键字,即:
1
2
3
4
5
6
7
8
class Derived : public Base
{
public:
virtualvoidf() override
{
std::cout << "Derived::f() const";
}
};
编译器会报错如下:
1
'virtual void Derived::f() const' marked 'override', but does not override
The LWG discussed this issue at the recent meeting in Kona Feb. 6-10, 2012. This is LWG issue 2113.
The LWG decided to mark LWG 2113 as NAD (not a defect), with the rationale that the standard is already clear that existing classes such as containers and std::string can not be marked final by the implementation.
The discussion included the fact that while it may be frowned on to derive from such classes, it is clearly legal to do so in C++98/03. And making it illegal in C++11 would break far too much code.
其实,前面已经提到了,C++11中引入了final就是为了终结继承,不过这种也分为两种:函数和类。
函数
如果想要一个函数不再被其子类覆盖,只需要在函数后加final即可:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Base
{
public:
virtualvoidf()
{
std::cout << "Base::f()";
}
};
class Derived : public Base
{
public:
voidf() final
{
std::cout << "Derived::f()";
}
};
此时,如果有另外一个类继承于Derived,且覆写了f()函数,即:
1
2
3
4
5
class Derived1 : public Derived
{
public:
voidf(){}
};
那么编译器则会报如下错误:
1
error: virtual function 'virtual void d::f()' overriding final function
类
如果想要一个类不被继承,则在该类的定义后面加上final即可:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Base
{
public:
virtualvoidf()
{
std::cout << "Base::f()";
}
};
class Derived final : public Base
{
public:
voidf() final
{
std::cout << "Derived::f()";
}
};
此时,如果某个类继承与Derived,则编译器会报如下错误:
1
error: cannot derive from 'final' base 'Derived' in derived type 'Derived1'